package com.ctrl.riveradministrator.mvp.presenter;

import android.util.Log;

import com.ctrl.riveradministrator.base.BaseObserver;
import com.ctrl.riveradministrator.base.BasePresenter;
import com.ctrl.riveradministrator.common.Constants;
import com.ctrl.riveradministrator.http.download.DownloadListener;
import com.ctrl.riveradministrator.mvp.model.RiverInfo;
import com.ctrl.riveradministrator.mvp.view.activity.river_info.RiverInfoView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RiverInfoPresenter extends BasePresenter<RiverInfoView> {

    public RiverInfoPresenter(RiverInfoView baseView) {
        super(baseView);
    }

    public void getRiverPolicy(String pageNumb, String pageSize){
        Map<String, String> map = new HashMap<>();
        map.put("pageNumb", pageNumb);
        map.put("pageSize", pageSize);
        attachView(apiService.getRiverInfo(map),new BaseObserver<RiverInfo>(getBaseView()){

            @Override
            public void onSuccess(RiverInfo model) {
                Log.d("Tgh", "onSuccess: ");
            }

            @Override
            public void onSuccess(List<RiverInfo> model) {
                getBaseView().showMessage(model);
            }

            @Override
            public void onFailed(String msg) {
                Log.d("Tgh", "onFailed: "+msg);
            }
        });
    }

    public void downloadFile(String u, DownloadListener downloadListener) {
        //下载路径，如果路径无效了，可换成你的下载路径
        final String url = Constants.BASE_URL_ + u;
        final long startTime = System.currentTimeMillis();
        Log.i("DOWNLOAD", "startTime=" + startTime);

        Request request = new Request.Builder().url(url).build();
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                e.printStackTrace();
                Log.i("DOWNLOAD", "download failed");
                downloadListener.onError("下载错误");
            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                //储存下载文件的目录
                File dir = new File(Constants.APP_ROOT_PATH + Constants.DOWNLOAD_DIR);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir,url.substring(url.lastIndexOf("/") + 1));
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        downloadListener.onProgress(progress);
                    }
                    fos.flush();
                    //下载完成
                    downloadListener.onCompleted(file);
                } catch (Exception e) {
                    e.printStackTrace();
                    downloadListener.onError(e.getMessage());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }

                }
            }
        });
    }
}
